package com.example.concurrent;

import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author houyangfan
 * @version 1.0
 * @date 2022/6/30 19:17
 *
 * 该示例用于比较使用 CopyOnWriteArrayList 和普通加锁方式 ArrayList 的读写性能
 */
@RestController
public class CopyOnWriteList {


    // 测试并发写的功能
    public static void testWrite(){
        List<Integer> copyOnWriteList = new CopyOnWriteArrayList<>();
        List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>());
        StopWatch stopWatch = new StopWatch();
        int loopCount = 100000;
        stopWatch.start("write:copyOnWrite");
        //循环100000并发在copyOnWriteList写入随机数据
        IntStream.rangeClosed(1,loopCount).parallel().forEach(i -> copyOnWriteList.add(ThreadLocalRandom.current().nextInt(loopCount)));
        stopWatch.stop();
        stopWatch.start("write:synchronizedList");
        //循环100000并发在copyOnWriteList写入随机数据
        IntStream.rangeClosed(1,loopCount).parallel().forEach(i -> synchronizedList.add(ThreadLocalRandom.current().nextInt(loopCount)));
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
        System.out.println("copyOnWriteList:"+ copyOnWriteList.size());
        System.out.println("synchronizedList:"+ synchronizedList.size());

    }

    public static void addAll(List<Integer> list){
        list.addAll(IntStream.rangeClosed(1, 1000000).boxed().collect(Collectors.toList()));
    }
    // 测试并发读的功能
    public static void testRead(){
        List<Integer> copyOnWriteList = new CopyOnWriteArrayList<>();
        List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>());
        addAll(copyOnWriteList);
        addAll(synchronizedList);
        StopWatch stopWatch = new StopWatch();
        int loopCount = 1000000;
        int count = copyOnWriteList.size();
        stopWatch.start("write:copyOnWrite");
        //循环100000并发在copyOnWriteList写入随机数据
        IntStream.rangeClosed(1,loopCount).parallel().forEach(i -> copyOnWriteList.get(ThreadLocalRandom.current().nextInt(count)));
        stopWatch.stop();
        stopWatch.start("write:synchronizedList");
        //循环100000并发在copyOnWriteList写入随机数据
        IntStream.rangeClosed(1,loopCount).parallel().forEach(i -> synchronizedList.get(ThreadLocalRandom.current().nextInt(count)));
        stopWatch.stop();

        System.out.println(stopWatch.prettyPrint());
        System.out.println("copyOnWriteList:"+ copyOnWriteList.size());
        System.out.println("synchronizedList:"+ synchronizedList.size());

    }

    public static void main(String[] args) {

        testRead();
    }
}
